package cn.cdzdjd.service.impl;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import cn.cdzdjd.exception.ErrorCode;
import cn.cdzdjd.exception.RenException;
import cn.cdzdjd.service.AcfunService;
import cn.cdzdjd.util.JsoupUtil;
import cn.cdzdjd.util.UrlUtil;
import cn.cdzdjd.vo.VideoInfoVO;

@Service
public class AcfunServiceImpl implements AcfunService {
	private final String baseUrl = "https://www.acfun.cn/v/";

	@Override
	public VideoInfoVO getVideoInfo(String url) {
		String final_url = "";
		try {
			if (url.contains("?")) {
				Map<String, String> map = UrlUtil.convertUrlParamsToMap(new URL(url));
				final_url = baseUrl + "ac" + map.get("ac");
			} else {
				final_url = url;
			}
			Document document = JsoupUtil.getDocument(final_url);
			Element element = document.body();
			Elements scripts = element.getElementsByTag("script");
			Element script = scripts.get(6);
			String pageInfo = script.data().split("\\;")[0].trim();
			int head = StringUtils.ordinalIndexOf(pageInfo, "{", 1);
			String jsonStr = StringUtils.substring(pageInfo, head);
			JSONObject json = new JSONObject(jsonStr);
			String title = json.getString("title");
			String coverUrl = json.getString("coverUrl");
			JSONObject currentVideoInfo = json.getJSONObject("currentVideoInfo");
			String ksPlayStr = currentVideoInfo.getString("ksPlayJson");
			JSONObject ksPlayJson = new JSONObject(ksPlayStr);
			JSONObject videoInfo = ksPlayJson.getJSONArray("adaptationSet").getJSONObject(0)
					.getJSONArray("representation").getJSONObject(0);
			String videoUrl = videoInfo.getString("url");
			List<String> videoList = new ArrayList<>();
			videoList.add(UrlUtil.setHttps(videoUrl));
			List<String> posterList = new ArrayList<>();
			posterList.add(UrlUtil.setHttps(coverUrl));
			return new VideoInfoVO(videoList, posterList, title, null);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RenException(ErrorCode.PARSE_ERROR, "解析失败");
		}

	}

}
